/**
* Author: Drew Goldberg
* CSCI 5828: HW3
* March 1, 2012
*/

package goldberg.drew.twitter;

import java.io.IOException;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


public class SequentialTwitter extends Twitter {
  
  /** request 16 pages of 200 tweets for the userName argument, and written/appended to file argument
  * @param userName	twitter account userName
  * @param file		The file that the twitter request will be written to.
  * @return void 
  */
  public void getUserTweets(final String userName, final String filePath) {
	    
    		for(int i = 0; i < 16; i++) {
			final int pageNumber = i+1;					
			try {	
				System.out.println("Retreiving User " + userName + " page " + pageNumber);				
				final BufferedInputStream in = new BufferedInputStream(new URL("http://api.twitter.com/1/statuses/user_timeline.xml?id="+userName+"&count=200&page="+pageNumber).openStream());
				final FileOutputStream fos = new FileOutputStream(filePath, true);
				final BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
				byte[] data = new byte[1024];
				int x = 0;		
				System.out.println("Writing to user " + userName + ". Write count " + pageNumber);				
				while((x=in.read(data,0,1024))>0){
				   bout.write(data, 0, x);
				}
				bout.close();
				in.close();					
			}
			catch (IOException e) {
					System.out.println("Failed at userName " + userName + " page " + pageNumber);
					e.printStackTrace();
			}

		}
		
	 }


  public static void main(final String[] args)  throws IOException, InterruptedException { 
 	final long start = System.nanoTime();
	final String topDirectory = "usersSequential/";	   
	SequentialTwitter sequentialTwitter = new SequentialTwitter();    
	sequentialTwitter.createUsers(topDirectory);
	for(final String key : users.keySet()) {										
		sequentialTwitter.getUserTweets(key, users.get(key).toString());
	}
	final long end = System.nanoTime();
	System.out.println("Time (seconds) taken " + (end - start)/1.0e9);  
 }
}

